package org.darcy.service.impl;

import java.util.Date;
import java.util.List;

import org.darcy.dao.SysUserMapper;
import org.darcy.entity.SysUser;
import org.darcy.framework.blog.business.enums.UserTypeEnum;
import org.darcy.framework.blog.exception.BlogCommentException;
import org.darcy.framework.blog.exception.BlogException;
import org.darcy.framework.blog.holder.RequestHolder;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.util.IpUtil;
import org.darcy.framework.util.PasswordUtil;
import org.darcy.model.SysUserModel;
import org.darcy.model.UserPwd;
import org.darcy.service.SysUserRoleService;
import org.darcy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户
 */
@Service
@Slf4j
public class SysUserServiceImpl extends GenericServiceImpl<SysUser> implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private SysUserRoleService SysUserRoleService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int update(SysUser user) {
		Assert.notNull(user, "User不可为空！");
		user.setUpdateTime(new Date());
		if (!StringUtils.isEmpty(user.getPassword())) {
			try {
				user.setPassword(PasswordUtil.encrypt(user.getPassword(), user.getUsername()));
			} catch (Exception e) {
				e.printStackTrace();
				throw new BlogCommentException("密码加密失败");
			}
		} else {
			user.setPassword(null);
		}
		return sysUserMapper.updateById(user);
	}

	/**
	 * 更新用户最后一次登录的状态信息
	 *
	 * @param user
	 * @return
	 */
	@Override
	public SysUser updateUserLastLoginInfo(SysUser user) {
		if (user != null) {
			user.setLoginCount(user.getLoginCount() + 1);
			user.setLastLoginTime(new Date());
			user.setLastLoginIp(IpUtil.getRealIp(RequestHolder.getRequest()));
			user.setPassword(null);
			this.update(user);
		}
		return user;
	}

	/**
	 * 根据用户名查找
	 *
	 * @param userName
	 * @return
	 */
	@Override
	public SysUser getByUserName(String username) {
		QueryWrapper<SysUser> q = new QueryWrapper<SysUser>();
		q.eq("username", username);
		SysUser sysUser = this.sysUserMapper.selectOne(q);
		return sysUser;
	}

	/**
	 * 通过角色Id获取用户列表
	 *
	 * @param roleId
	 * @return
	 */
	@Override
	public List<SysUser> listByRoleId(Long roleId) {
		List<SysUser> sysUsers = sysUserMapper.listByRoleId(roleId);
		return sysUsers;
	}

	/**
	 * 修改密码
	 *
	 * @param userPwd
	 * @return
	 */
	@Override
	public boolean updatePwd(UserPwd userPwd) throws Exception {
		if (!userPwd.getNewPassword().equals(userPwd.getNewPasswordRepeat())) {
			throw new BlogException("新密码不一致！");
		}
		SysUser user = this.getById(userPwd.getId());
		if (null == user) {
			throw new BlogException("用户编号错误！请不要手动操作用户ID！");
		}

		if (!user.getPassword().equals(PasswordUtil.encrypt(userPwd.getPassword(), user.getUsername()))) {
			throw new BlogException("原密码不正确！");
		}
		user.setPassword(userPwd.getNewPassword());
		this.update(user);
		return true;
	}

	@Override
	public SysUser getByUuidAndSource(String uuid, String source) {
		if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(source)) {
			return null;
		}
		QueryWrapper<SysUser> q = new QueryWrapper<SysUser>();
		q.eq("uuid", uuid).eq("source", source);
		SysUser user = sysUserMapper.selectOne(q);
		return user;
	}

	@Override
	public SysUserModel register(SysUserModel user) {
		SysUserModel data = new SysUserModel();
		SysUser record = this.getByUserName(user.getUsername());
		if (record != null) {
			data.setRegisterCode(-1);
			data.setRegisterMsg("用户名已存在");
			return data;
		}
		String dbPassword = null;
		try {
			dbPassword = PasswordUtil.encrypt(user.getPassword(), user.getUsername());
		} catch (Exception e) {
			log.error("用户注册密码设置出错", e);
			data.setRegisterCode(-2);
			data.setRegisterMsg("用户注册密码设置出错");
			return data;
		}
		record = new SysUser();
		record.setUsername(user.getUsername());
		record.setPassword(dbPassword);
		this.insert(record);
		SysUserRoleService.addUserRole(record.getId(), UserTypeEnum.USER.ordinal() + "");
		data.setRegisterMsg("用户注册成功");
		data.setRegisterCode(0);
		data.setId(record.getId());
		return data;
	}

}
